import axios from 'axios';
import Vue from 'vue';
// 输入一个值,返回其数据类型
export const type = para => {
  return Object.prototype.toString.call(para).slice(8, -1);
};
// 数字超过999显示省略号-99可调整
export const num_filter = val => {
  val = val ? val - 0 : 0;
  if (val > 999) {
    return '…';
  } else {
    return val;
  }
};
// 数字超过99显示99+
export const ninenum_filter = val => {
  val = val ? val - 0 : 0;
  if (val > 99) {
    return '99+';
  } else {
    return val;
  }
};
// 银行卡号分割
export const bank_filter = val => {
  val += '';
  val = val
    .replace(/(\s)/g, '')
    .replace(/(\d{4})/g, '$1 ')
    .replace(/\s*$/, '');
  return val;
};
// 获取文件的后缀
export const getFileType = file => file.substr(file.lastIndexOf('.') + 1);

// 校验手机号码:phone,可以为数字或字符串，允许有空格。
export function isValidPhone(phone) {
  const phoneReg = /^1[3456789]\d{9}$/;
  if (phoneReg.test(phone.toString().replace(/\s+/g, ''))) {
    return true;
  }
  return false;
}
// 手机号脱敏
export const hideMobile = mobile => {
  return mobile.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2');
};
// 大小写转换，type 1-全大写 2-全小写 3-首字母大写
export const turnCase = (str, type) => {
  switch (type) {
    case 1:
      return str.toUpperCase();
    case 2:
      return str.toLowerCase();
    case 3:
      return str[0].toUpperCase() + str.substring(1).toLowerCase();
    default:
      return str;
  }
};
// 判断手机是Andoird还是IOS
export const getOSType = () => {
  const u = navigator.userAgent;
  const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;
  const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
  if (isIOS) {
    return 1;
  }
  if (isAndroid) {
    return 2;
  }
  return 3;
};
// 防抖 只执行最后一次点击
export const debounce = (fn, t) => {
  const delay = t || 1000;
  let timer;
  return function() {
    const args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      timer = null;
      fn.apply(this, args);
    }, delay);
  };
};
// 节流，一段时间内只执行一次
export const throttle = (fn, t) => {
  let last;
  let timer;
  const interval = t || 500;
  return function() {
    const args = arguments;
    const now = +new Date();
    if (last && now - last < interval) {
      clearTimeout(timer);
      timer = setTimeout(() => {
        last = now;
        fn.apply(this, args);
      }, interval);
    } else {
      last = now;
      fn.apply(this, args);
    }
  };
};
// 深拷贝
export const deepClone = source => {
  const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象
  for (const keys in source) {
    // 遍历目标
    if (source.prototype.hasOwnProperty.call(keys)) {
      if (source[keys] && typeof source[keys] === 'object') {
        // 如果值是对象，就递归一下
        targetObj[keys] = source[keys].constructor === Array ? [] : {};
        targetObj[keys] = deepClone(source[keys]);
      } else {
        // 如果不是，就直接赋值
        targetObj[keys] = source[keys];
      }
    }
  }
  return targetObj;
};

// 数组对象根据字段去重，arr 要去重的数组，key 根据去重的字段名
export const uniqueArrayObject = (arr = [], key = 'id') => {
  if (arr.length === 0) return;
  let list = [];
  const map = {};
  arr.forEach(item => {
    if (!map[item[key]]) {
      map[item[key]] = item;
    }
  });
  list = Object.values(map);

  return list;
};
/**
 * 滚动到指定元素位置
 * @example smoothScroll('#target'); // 平滑滚动到 ID 为 target 的元素
 */
export const smoothScroll = element => {
  document.querySelector(element).scrollIntoView({
    behavior: 'smooth'
  });
};
// 前端生成uuid
export const uuid = () => {
  const temp_url = URL.createObjectURL(new Blob());
  const uuid = temp_url.toString();
  URL.revokeObjectURL(temp_url); // 释放这个url
  return uuid.substring(uuid.lastIndexOf('/') + 1);
};
// 去掉空格的方法
export function Trim(str, is_global) {
  var result;
  result = str.replace(/(^\s+)|(\s+$)/g, '');
  if (is_global.toLowerCase() === 'g') {
    result = result.replace(/\s/g, '');
  }
  return result;
}

// 银行卡号校验
export function checkBankCard(fieldId) {
  var fieldValue = fieldId.replace(/\s+/g, '');
  if (fieldValue !== '' && !/(^\d{16,19}$)$/i.test(fieldValue)) {
    console.log('您填写的银行卡号位数不正确，请核对');
    return false;
  }
  return true;
}
/**
 *金额格式化
 * @param {number} number	要格式化的数字
 * @param {number} decimals	保留几位小数
 * @param {number} dec_point	小数点符号
 * @param {number} thousands_sep	千分位符号
 * @example moneyFormat(10000000) // 10,000,000.00
 * @example moneyFormat(10000000, 3, '.', '-') // 10-000-000.000
 */
export const moneyFormat = (number, decimals, dec_point, thousands_sep) => {
  number = (number + '').replace(/[^0-9+-Ee.]/g, '');
  const n = !isFinite(+number) ? 0 : +number;
  const prec = !isFinite(+decimals) ? 2 : Math.abs(decimals);
  const sep = typeof thousands_sep === 'undefined' ? ',' : thousands_sep;
  const dec = typeof dec_point === 'undefined' ? '.' : dec_point;
  let s = '';
  const toFixedFix = function(n, prec) {
    const k = Math.pow(10, prec);
    return '' + Math.ceil(n * k) / k;
  };
  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
  const re = /(-?\d+)(\d{3})/;
  while (re.test(s[0])) {
    s[0] = s[0].replace(re, '$1' + sep + '$2');
  }
  if ((s[1] || '').length < prec) {
    s[1] = s[1] || '';
    s[1] += new Array(prec - s[1].length + 1).join('0');
  }
  return s.join(dec);
};
// 身份证号格式化
Vue.filter('idCardFormat', function(dateStr) {
  if (dateStr == null) {
    return;
  }
  let idNo = dateStr.substring(0, 3);
  for (let i = 0; i < dateStr.length - 6; i++) {
    idNo = idNo + '*';
  }
  idNo = idNo + dateStr.substring(dateStr.length - 3);
  return idNo;
});

// 银行卡号\电子账户号中间*处理
Vue.filter('NumberFormat', function(dateStr) {
  if (dateStr == null) {
    return;
  }
  let carNumber = dateStr.substring(0, 4);
  for (let i = 0; i < dateStr.length - 8; i++) {
    carNumber = carNumber + '*';
  }
  carNumber = carNumber + dateStr.substring(dateStr.length - 4);
  return carNumber;
});
// 银行卡号/电子账户号中间*处理 四位添加空格
Vue.filter('bankCardFormat', function(dateStr) {
  if (dateStr == null) {
    return;
  }
  const spaces = '&nbsp;&nbsp;&nbsp;';
  let carNumber = dateStr.substring(0, 4) + spaces;
  for (let i = 0; i < dateStr.length - 8; i++) {
    if (i === parseInt((dateStr.length - 8) / 2)) {
      carNumber = carNumber + '*' + spaces;
    } else {
      carNumber = carNumber + '*';
    }
  }
  carNumber = carNumber + spaces + dateStr.substring(dateStr.length - 4);
  return carNumber;
});
/**
 * 判断数值是否为空
 * @param str	判断的值
 * @returns {boolean}
 */
export function isNull(str) {
  if (/\d+/.test(str)) {
    str += '';
  }
  if (
    str === 'null' ||
    str === null ||
    typeof str === 'undefined' ||
    str === 'undefined' ||
    str === '' ||
    str === '{}' ||
    (typeof str === 'object' && (JSON.stringify(str) === '{}' || JSON.stringify(str) === '[]'))
  ) {
    return true;
  }
  return false;
}

// 账号脱敏处理
export function accountDesen(num) {
  return num.substring(0, 4) + '*****' + num.substring(num.length - 4, num.length);
}
// 检测是否为空对象
export function isEmpty(obj) {
  return Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
}
// 校验文件类型
export function checkFileType(name, accept) {
  var type = name.slice(name.lastIndexOf('.') + 1);
  if (typeof accept === 'object') {
    return accept.some(s => s === type);
  } else if (typeof accept === 'string') {
    return accept === type;
  }
}
// 监听ios软键盘收起
export function focusout() {
  document.body.addEventListener('focusout', () => {
    // 软键盘收起的事件处理
    setTimeout(() => {
      const scrollHeight = document.documentElement.scrollTop || document.body.scrollTop || 0;
      window.scrollTo(0, Math.max(scrollHeight - 1, 0));
    }, 100);
  });
}
// 验证不能包含字母
export const isNoWord = value => /^[^A-Za-z]*$/g.test(value);
// 验证手机号中国(严谨), 根据工信部2019年最新公布的手机号段
export const isMPStrict = value =>
  /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-7|9])|(?:5[0-3|5-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1|8|9]))\d{8}$/g.test(
    value
  );
// 验证email(邮箱)
export const isEmail = value =>
  /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/g.test(
    value
  );
// 验证身份证号(2代,18位数字),最后一位是校验位,可能为数字或字符X
export const isIDCard = value =>
  /(^\d{8}(0\d|10|11|12)([0-2]\d|30|31)\d{3}$)|(^\d{6}(18|19|20)\d{2}(0\d|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$)/g.test(
    value
  );
// 获取窗口可视范围的高度
export function getClientHeight() {
  let clientHeight = 0;
  if (document.body.clientHeight && document.documentElement.clientHeight) {
    clientHeight =
      document.body.clientHeight < document.documentElement.clientHeight
        ? document.body.clientHeight
        : document.documentElement.clientHeight;
  } else {
    clientHeight =
      document.body.clientHeight > document.documentElement.clientHeight
        ? document.body.clientHeight
        : document.documentElement.clientHeight;
  }
  return clientHeight;
}
// 获取窗口可视范围宽度
export function getPageViewWidth() {
  const d = document;
  const a = d.compatMode === 'BackCompat' ? d.body : d.documentElement;
  return a.clientWidth;
}
// set数组去重
export function uniqueArr(arr) {
  return [...new Set(arr)];
}
/**
 * 文件下载
 * @param api 接口
 * @param params 请求参数
 * @param fileName 文件名
 * @example downloadFile('/api/download', {id}, '文件名')
 */
export const fileDownLoad = (api, params, fileName, type = 'get') => {
  axios({
    method: type,
    url: api,
    responseType: 'blob',
    params: params
  })
    .then(res => {
      const str = res.headers['content-disposition'];
      if (!res || !str) {
        return;
      }
      let suffix = '';
      // 截取文件名和文件类型
      if (str.lastIndexOf('.')) {
        fileName ? '' : (fileName = decodeURI(str.substring(str.indexOf('=') + 1, str.lastIndexOf('.'))));
        suffix = str.substring(str.lastIndexOf('.'), str.length);
      }
      //  如果支持微软的文件下载方式(ie10+浏览器)
      if (window.navigator.msSaveBlob) {
        try {
          const blobObject = new Blob([res.data]);
          window.navigator.msSaveBlob(blobObject, fileName + suffix);
        } catch (e) {
          console.log(e);
        }
      } else {
        //  其他浏览器
        const url = window.URL.createObjectURL(res.data);
        const link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', fileName + suffix);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
      }
    })
    .catch(err => {
      console.log(err.message);
    });
};
// 图片转base64
export default function getBase64Image(img) {
  var canvas = document.createElement('canvas');
  canvas.width = img.width * 0.7;
  canvas.height = img.height * 0.7;
  var ctx = canvas.getContext('2d');
  ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);
  var dataURL = canvas.toDataURL('image/jpeg', 0.5);
  canvas = null;
  return dataURL;
}
// base64转file
export const base64ToFile = (base64, filename) => {
  const arr = base64.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const suffix = mime.split('/')[1]; // 图片后缀
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], `${filename}.${suffix}`, { type: mime });
};
// blob转file
export const blobToFile = (blob, fileName) => {
  blob.lastModifiedDate = new Date();
  blob.name = fileName;
  return blob;
};
// file转base64
export const fileToBase64 = file => {
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = function(e) {
    return e.target.result;
  };
};
// 内容复制
export const copyContent = content => {
  if (!content) {
    return false;
  }
  const input = document.createElement('input');
  input.value = content;
  input.style.position = 'absolute';
  document.documentElement.appendChild(input);
  input.select();
  document.execCommand('copy');
  document.documentElement.removeChild(input);
  return true;
};
// 标签转义(预防XSS攻击)
export const encodeHtml = param => {
  if (param.length === 0) return '';
  return (param + '')
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/\x60/g, '&#96;')
    .replace(/\x27/g, '&#39;')
    .replace(/\x22/g, '&quot;');
};
// 将字符串中的实体转换为原字符
export const decodeHtml = param => {
  return (param + '')
    .replace(/&quot;/g, '\x22')
    .replace(/&#0*39;/g, '\x27')
    .replace(/&#0*96;/g, '\x60')
    .replace(/&gt;/g, '>')
    .replace(/&lt;/g, '<')
    .replace(/&amp;/g, '&');
};
// H5软键盘缩回、弹起回调
// 当软件键盘弹起会改变当前 window.innerHeight，监听这个值变化 [down 当软键盘弹起后，缩回的回调,up 当软键盘弹起的回调]
export const softKeyboard = (down, up) => {
  var clientHeight = window.innerHeight;
  down = typeof down === 'function' ? down : function() {};
  up = typeof up === 'function' ? up : function() {};
  window.addEventListener('resize', () => {
    var height = window.innerHeight;
    if (height === clientHeight) {
      down();
    }
    if (height < clientHeight) {
      up();
    }
  });
};
